package com.carassistant.beta.common;
  
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.TypedValue;
import android.view.WindowManager;

import com.carassistant.beta.R;
import com.carassistant.beta.db.CarAssSharePre;
import com.carassistant.beta.home.HomeActivity;
import com.carassistant.beta.music.MusicMainActivity;
import com.carassistant.beta.music.MusicMainActivity;
import com.carassistant.beta.music.util.ScanUtil;
/**
 * 全局Application
 * @author Alen
 * */
public class CarAssistantApp extends Application{
	private static final String TAG = "CarAssistantApp";  
	
	private static Drawable CARADIO_BG_PORT;
	public static int screenMax;
	public static int screenMin;
	@Override
	public void onCreate() { 
		super.onCreate();
//		MusicSharePre.initSharePre(getApplicationContext());
//		ContentValues values = DBOperation.getDefineBG(this); 
//		 
//		if (values != null) {
//			byte[] port = values.getAsByteArray(DBOperation.PORT_BG);
//			byte[] land = values.getAsByteArray(DBOperation.LAND_BG);
//			CARADIO_BG_PORT = new BitmapDrawable(BitmapFactory.decodeByteArray(port, 0, port.length));
//			CARADIO_BG_PORT.setAlpha(100);
//			CARADIO_BG_LAND = new BitmapDrawable(BitmapFactory.decodeByteArray(land, 0, land.length));
//			CARADIO_BG_LAND.setAlpha(100);
//		} else {
//			setDefaultBG(this);
//		}  
		
		new Runnable() {
			@Override
			public void run() {
				new ScanUtil(CarAssistantApp.this).scanMusicFromDB();
			}
		}.run();
	}
    
	public static Drawable getCaradioBg(Context mContext){
		return CARADIO_BG_PORT;
	}
	
	public static void setCaradioBG(Drawable port, Drawable land){
		if (port != null ) {
			CARADIO_BG_PORT = port;
			CARADIO_BG_PORT.setAlpha(100);
		}
	}
	
	public static void setDefaultBG(Context context){
//		CARADIO_BG_PORT = context.getResources().getDrawable(R.drawable.caradio_background_port);  
	}
	

	public static int getScreenHeight(float divide){ 
		return (int)(screenMax / divide);
	}
	
	public static int getScreenWidth(float divide){ 
		return (int)(screenMin / divide);
	} 
	
	public static boolean getBTState(){ 
		return false;
	}
	
	/**
	 * 判断是否有网络
	 */
	public static boolean checkNetwork(final Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null) {
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		} 
		return false;
	} 
	 
	public static boolean checkApkExist(Context context, String packageName) { 
		try {
			context.getPackageManager().getApplicationInfo(packageName,
					PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}
	

	/**
	 * 返回当前的应用是否处于前台显示状态  
	 * @param $packageName
	 * @return
	 */
	public static boolean isCaradioTop(Context context) {
		ActivityManager am = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
		if (list.size() == 0){
			return false;
		}
			
		for (ActivityManager.RunningAppProcessInfo process : list) {
			if (process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
					&& process.processName.equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断是否后天有音乐播放器在播放,根据后天运行的任务来判断
	 * @param context
	 * @param musicPkgs
	 * @return null 没有播放器在播放
	 *         String 正在运行的播放器的包名
	 */
	public static String hasMusicPlayerRunning(Context context, ArrayList<String> musicPkgs) {
		ActivityManager am = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(50);
		if (list.size() == 0){
			return null;
		}
			
		for (ActivityManager.RunningTaskInfo process : list) {
			String temp = process.baseActivity.getPackageName();
			Log.v(TAG, "background running task package name=" + temp);
			for (String pkgName : musicPkgs) {
				if (pkgName.equals(temp)) {
					return pkgName;
				} 
			} 
		}
		return null;
	}
	
	/**
	 * 判断是否后天有音乐播放器在播放，根据后台的服务来判断
	 * @param context
	 * @param musicPkgs
	 * @return
	 */
	public static boolean hasMusicPlayerRunning2(Context context, String[] musicPkgs) {
		ActivityManager am = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> list = am.getRunningServices(100);
		if (list.size() == 0){
			return false;
		}
			
		for (ActivityManager.RunningServiceInfo process : list) {
			String temp = process.service.getPackageName();
			Log.v(TAG, "background running service package name=" + temp);
			for (String pkgName : musicPkgs) {
				if (pkgName.equals(temp)) {
					return true;
				} 
			} 
		}
		return false;
	}
	
	public static boolean isSerivceRunning(Context context, String serviceClassName){
		boolean isRunning = false;
		ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> infos = am.getRunningServices(40); 
		for(RunningServiceInfo info : infos){ 
		      if(info.service.getClassName().equals(serviceClassName)){
		    	  isRunning = true;
		    	  break;
		      }
		} 
		return isRunning;
	}
 

	public static final String MUSIC_SERVICE_NAME = "com.carstream.beta.music.service.MusicService";
	public static final String ABOUT_MAIN_NAME = "com.carstream.beta.home.AboutActivity";
	public static void startMusicService(Context mContext, long musicID){
		CarAssSharePre.savePlayingMusicID(musicID);
		CarAssSharePre.saveMusicProgress(0);
		startMusicService(mContext);
	}
	
	public static void startMusicService(Context mContext){
		Intent startMusicServie = new Intent(); 
//		startMusicServie.setAction(MusicTools.MUSIC_SERVICE_START_INTENT);
		mContext.startService(startMusicServie); 
	}
	
	public static Intent goNotificationIntent(Activity context){
		Intent intent = new Intent(Intent.ACTION_MAIN);  
		intent.addCategory(Intent.CATEGORY_LAUNCHER);  
		intent.setComponent(new ComponentName(context.getPackageName(), context.getPackageName() + "." + context.getLocalClassName()));  
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		return intent;
	}
	
	public static Intent stratCaradioActivity(Context context){
		Intent intent = new Intent(Intent.ACTION_MAIN);  
		intent.addCategory(Intent.CATEGORY_LAUNCHER);  
		intent.setClass(context, HomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		return intent;
	}
	
	public static ComponentName getTopActivity(Context mContext) {
		ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(100); 
		for (RunningTaskInfo task: tasksInfo) { 
			if (task.baseActivity.getPackageName().equals(mContext.getPackageName())) {
				Log.v("tttt", task.topActivity.toString());
				return task.topActivity;
			} 
		}
		return new ComponentName(mContext, HomeActivity.class);
	}  
	
	public final static String POWER_LOCK_NAME = "carstudio_lock_name";
	public static WakeLock wakeLock;
	public static void neverScreenOff(Context mContext) {
		if (wakeLock == null) {
			wakeLock = ((PowerManager)mContext.getSystemService("power")).newWakeLock(
					PowerManager.SCREEN_BRIGHT_WAKE_LOCK, POWER_LOCK_NAME);
			wakeLock.acquire();  
		}   
	}  
	
	public static void cancelScreenOff(Context mContext) { 
		if (wakeLock != null) {
			wakeLock.release();
			wakeLock = null;
		}  
	} 
	
	public static void startToMusicHome(CarAssistantActivity activity){
		if (!activity.isActvityHaveOpen(MusicMainActivity.class)) {
			activity.startActivity(new Intent(activity, MusicMainActivity.class));
		};
	}
	
	/**
	 * 设置屏幕的亮度
	 * @param light 亮度值  0-1之间
	 * */
	private static void setScreenBright(Activity activity, int bright) {  
		if (bright > 255) {
			bright = 255;
		} 
		
		WindowManager.LayoutParams params = activity.getWindow().getAttributes();
		params.screenBrightness = Float.valueOf(bright) * (1f / 255f);
		activity.getWindow().setAttributes(params); 
				
		Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);    
		android.provider.Settings.System.putInt(activity.getContentResolver(), 
				Settings.System.SCREEN_BRIGHTNESS, bright);  
		activity.getContentResolver().notifyChange(uri, null);
	}
	
	/**
	 * 获取屏幕的亮度
	 * @param light 亮度值  0-5之间
	 * */
	public static int getScreenBrightness(Context context) {
		int value = 0;
		int brightLevel = 0;
		ContentResolver cr = context.getContentResolver();
		try {
			value = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS) - 30;
		} catch (SettingNotFoundException e) {
			Log.v("", e.toString());
		}
		if (value > 0 && value <= 43) {
			brightLevel = 0; 
		} else if (value > 43 && value <= 96) {
			brightLevel = 1; 
		}else if (value > 96 && value <= 149) {
			brightLevel = 2; 
		} else if (value > 149 && value <= 202) {
			brightLevel = 3; 
		} else if (value > 202 && value <= 255) {
			brightLevel = 4; 
		}
		return brightLevel;
	}
	
	/** stop audto adjust light */
	public static void stopAutoBrightness(Context context) {
		Settings.System.putInt(context.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
	}
	
	public static boolean isAutoBrightness(Context context){ 
		int isAuto = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 100);
		if (isAuto == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
			return true;
		} else {
			return false;
		}
	}
	
	public static void startAutoBrightness(Context context) {
		Settings.System.putInt(context.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
	}
 
	
	public static void saveBright(Activity activtiy, int progress){
		if (isAutoBrightness(activtiy)) {
			stopAutoBrightness(activtiy);
		}
		int currentBright = progress % 5; 
		setScreenBright(activtiy, currentBright * 53 + 43); 
	}
	
	public static boolean isGPSOpen(Context context){
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
	}
	
	public static float getSize(Context context, float value){
		return TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_SP, value, context.getResources().getDisplayMetrics());
	}
	

	/**
	 * 飞行模式是否打开
	 */
	public static boolean isPlaneState(Context context){
		return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
	}
	
	/**
	 * 关闭飞行模式
	 */
	public static void closeAirplaneMode(Context context){
		Settings.System.putInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0); 
		Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		intent.putExtra("state", false); 
		context.sendBroadcast(intent); 
	}
	
	private static final long VIBRATOR_TIME = 200;
	public static void philipsVobrator(Context context){ 
		if (CarAssSharePre.getSettingVibration()) {
			Vibrator vibrator = (Vibrator) context.getSystemService(VIBRATOR_SERVICE); 
			vibrator.vibrate(VIBRATOR_TIME);
		}
	}
	  
	public static MediaPlayer mp;  
	public static void playClickVoice(Context context){
		if (CarAssSharePre.getSettingSound()) {
			try {
				if (mp == null) {
					mp = new MediaPlayer(); 
				}   
				mp.reset();
				AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.button_click_voice);
	            if (afd == null)  return; 
	            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
	            afd.close();
	            
				final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
 	    		audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
 	    		audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), AudioManager.FLAG_VIBRATE);
 	    		mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
				
	            mp.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mp.start();
		} 
	}
	
	public static boolean isLargeScreen(){
		if (screenMax > 1000) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 根据手机分辨率从dp转成px
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f) - 15;
	}
	
	/**
	 * 将传递的汉字list转换成拼音List
	 * @param list
	 */
	public static List<String> getPinyinList(List<String> list){
		List<String> pinyinList = new ArrayList<String>();
		for(Iterator<String> i=list.iterator(); i.hasNext();) {
			String str = (String)i.next();
			try {
				String pinyin = getPinYin(str);
				pinyinList.add(pinyin);
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				e.printStackTrace();
			}
		}
		return pinyinList;
	}
	
    /**
     * 将中文转换成拼音
     * @param 拼音-汉字
     * @return
     */
    public static String getPinYin(String zhongwen)   
            throws BadHanyuPinyinOutputFormatCombination {   
  
        String zhongWenPinYin = "";   
        char[] chars = zhongwen.toCharArray();   
  
        for (int i = 0; i < chars.length; i++) {   
            String[] pinYin = PinyinHelper.toHanyuPinyinStringArray(chars[i], getDefaultOutputFormat());   
            // 当转换不是中文字符时,返回null   
            if (pinYin != null) {   
            	zhongWenPinYin += pinYin[0];   
            } else {   
                zhongWenPinYin += chars[i];   
            }   
        }   
        return zhongWenPinYin;   
    }   
  
    /**  
     * 输出格式  
     *   
     * @return  
     */  
    private static HanyuPinyinOutputFormat getDefaultOutputFormat() {   
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();   
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 大写   
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 没有音调数字   
        format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);// u显示   
        return format;   
    }   
}